package utils

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"net/http"
	"net/url"
	"regexp"
	"strings"
)

func MapToQueryString(data map[string]string) string {
	pairSlice := make([]string, 0, len(data))
	for key, value := range data {
		v := fmt.Sprintf("%v", value)
		pair := url.QueryEscape(key) + "=" + url.QueryEscape(v)
		pairSlice = append(pairSlice, pair)
	}
	return strings.Join(pairSlice, "&")
}

func CheckEmailFormat(email string) bool {
	pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*`
	reg := regexp.MustCompile(pattern)
	return reg.MatchString(email)
}


func GetHost(req *http.Request) string {
	logrus.Info("req:",req.Header)
	host1 := getValueFromHeader("Host", req.Header)
	host2 := getValueFromHeader("X-Forwarded-Host", req.Header)

	if host1 != "" {
		return host1
	}
	host3 := req.Host
	logrus.Info("host1:",host1)
	logrus.Info("host2:",host2)
	logrus.Info("host3:",host3)
	if len(host2) > 0 {
		return host2
	}
	return host3
}

func getValueFromHeader(name string, header http.Header) string {
	headerValues := header[name]
	if len(headerValues) == 0 {
		return ""
	}
	return headerValues[0]
}



